import json
import random

from django.http import HttpResponse, JsonResponse
from django.template import loader
from django.shortcuts import render

# from bigdata import settings
from .models import Student, Grade, DutyLog
from django.core.paginator import Paginator
from functools import wraps
import os


# Create your views here.
def my_custom_decorator(view_func):
    @wraps(view_func)
    def wrapper(request, *args, **kwargs):
        if request.session.get('userinfo') is None:
            template = loader.get_template('login.html')
            return HttpResponse(template.render({}, request))
        return view_func(request, *args, **kwargs)
    return wrapper  # 返回的叫做函数的引用


def index(request):
    template = loader.get_template('login.html')
    return HttpResponse(template.render({}, request))


def checklogin(request):
    username = request.POST['username']
    password = request.POST['password']
    # 我们应该动态查询数据库学生表
    is_exist = Student.objects.filter(user_name=username)
    if is_exist:
        # 进而判断账号密码
        if password == is_exist[0].password:
            # 少了一个写入session 在网站里存储登录用户信息的，能实现跨页面传递
            request.session['userinfo'] = {
                'username': username,
                'password': password,
                'img': is_exist[0].img
            }
            print('session写入了。。。。。。。。。。。。。。')
            return JsonResponse({'code': 1, 'msg': '登录成功'})
        else:
            return JsonResponse({'code': 0, 'msg': '密码错误'})
    else:
        return JsonResponse({'code': 0, 'msg': '该用户不存在，请联系后台管理员'})


@my_custom_decorator
def backend(request):
    # 查询session，将用户名和头像传递到前端页面
    user_info = request.session.get('userinfo')
    template = loader.get_template('backend.html')
    return HttpResponse(template.render(user_info, request))


@my_custom_decorator
def student_list(request):
    template = loader.get_template('student_list.html')
    return HttpResponse(template.render({}, request))


def student_api(request):
    # 从数据库中提取数据返回给前端，这才是正确
    # 怎么查询？
    info = Student.objects.all().order_by('-id')  # 查询全部 all()
    # （1）分页对象
    limit = request.GET.get('limit')
    paginator = Paginator(info, limit)
    count = paginator.count  # 查询全部数量
    # （2）获取某页对象
    visit_page_num = request.GET.get('page')
    page = paginator.page(visit_page_num)  # paginator.page(哪一页的数据)
    # print(page.object_list)
    data = []
    for x in page.object_list:
        data.append({"id": x.id, "username": x.user_name, "sex": x.sex, "city": x.address, "sign": x.sign,
                     "img": x.img})

    sut_info = {
        "code": 0,
        "count": count,
        "data": data,
        "msg": '返回成功'
    }
    return JsonResponse(sut_info)


@my_custom_decorator
def student_add(request):
    template = loader.get_template('student_add.html')
    return HttpResponse(template.render({}, request))


def student_add_api(request):
    user_name = request.POST.get('user_name')
    address = request.POST.get('address')
    sex = request.POST.get('sex')
    sign = request.POST.get('sign')
    img = request.POST.get('img')
    password = request.POST.get('password')
    print(img)
    print('是否获取到img')
    # 拿到前端提交的数据，接下来你该干啥
    res = Student.objects.create(user_name=user_name,
                           address=address,
                           sex=sex,
                           sign=sign,
                           img=img,
                           password=password
                           )
    sut_info = {
        "code": 0,
        "msg": '新增成功'
    }
    if res is None:
        sut_info['code'] = 1
        sut_info['msg'] = '插入失败'
    return JsonResponse(sut_info)


def student_del_api(request):
    id = request.POST.get('id')
    # 通过ID删除
    obj = Student.objects.get(id=id)
    res = obj.delete()
    sut_info = {
        "code": 0,
        "msg": '删除成功'
    }
    if res is None:
        sut_info['code'] = 1
        sut_info['msg'] = '删除失败'
    return JsonResponse(sut_info)


def img_upload(request):
    print(request.FILES)
    # 可以确定文件资源确实调用我们的接口
    # python文件上传
    # 获取文件上传资源
    file = request.FILES.get('file')
    # 文件存储的地址
    from bigdata import settings
    file_path = os.path.join(settings.BASE_DIR, 'static\\image\\' + file.name)
    # 文件url
    file_url = os.path.join('\\static\\image\\' + file.name)
    # 写入文件
    with open(file_path, 'wb') as uploaded_file:
        for chunk in file.chunks():
            uploaded_file.write(chunk)

    sut_info = {
        "code": 0,
        "file": file_url
    }
    return JsonResponse(sut_info)


def login_out(request):
    request.session.flush()
    info = {
        "code": 0,
        "msg": '退出成功'
    }
    return JsonResponse(info)


@my_custom_decorator
def student_edit(request):
    id = request.GET.get('id')
    # 在编辑页面渲染的时候，应该把id的这条数据内容显示出来
    obj = Student.objects.get(id=id)
    data = {
        'user_name': obj.user_name,
        'password': obj.password,
        'sex': obj.sex,
        'address': obj.address,
        'sign': obj.sign,
        'img': obj.img,
    }

    template = loader.get_template('student_edit.html')
    return HttpResponse(template.render(data, request))


def export_excel(request):
    # 4.1 新建一个Excel文件
    import xlwt
    df2 = xlwt.Workbook()
    # 4.2 新建一个工作表
    # 这里的name是工作表的名称
    table2 = df2.add_sheet('23大数据')
    # 4.3 写入数据到指定单元格
    # 在这里去开始写数据
    titles = ['序号', '姓名', '头像', '性别', '籍贯', '签名']
    # 注意：循环列表的同时，将对应索引下标也循环出来
    for i, k in enumerate(titles):
        table2.write(0, i, k)
    # 数据是不是要查询
    res = Student.objects.values('id', 'user_name', 'img', 'sex', 'address', 'sign')
    for i, k in enumerate(res):
        table2.write(i + 1, 0, k['id'])
        table2.write(i + 1, 1, k['user_name'])
        table2.write(i + 1, 2, k['img'])
        table2.write(i + 1, 3, k['sex'])
        table2.write(i + 1, 4, k['address'])
        table2.write(i + 1, 5, k['sign'])

    response = HttpResponse(content_type='application/vnd.ms-excel')
    response['Content-Disposition'] = 'attachment; filename="data2.xls"'
    # 4.4 保存文件
    df2.save(response)
    return response


@my_custom_decorator
def grade_add(request):
    student_id = request.GET.get('id')
    template = loader.get_template('grade/grade_add.html')
    return HttpResponse(template.render({"student_id": student_id}, request))


def grade_add_api(request):
    info = request.POST
    print(info)
    insert_data = {}
    for key, value in info.items():
        insert_data[key] = value
    print(insert_data)
    student_obj = Student.objects.get(id=insert_data['student_id'])
    # 拿到前端提交的数据，接下来你该干啥
    res = Grade.objects.create(python=insert_data['python'],
                           java=insert_data['java'],
                           vue=insert_data['vue'],
                           linux=insert_data['linux'],
                           student_id=student_obj,
                           )
    sut_info = {
        "code": 0,
        "msg": '新增成功'
    }

    if res is None:
        sut_info['code'] = 1
        sut_info['msg'] = '新增失败'

    return JsonResponse(sut_info)


@my_custom_decorator
def grade_list(request):
    # 查询grade表，将数据带到前端页面
    info = Grade.objects.all().values('python', 'java', 'student_id_id')
    python_list = []
    java_list = []
    students_list = []
    for key in info:
        python_list.append(key['python'])
        java_list.append(key['java'])
        name = Student.objects.filter(id=key['student_id_id']).first()
        students_list.append(str(name))

    data = {
        'python_score': python_list,
        'java_score': java_list,
        'name': students_list
    }
    template = loader.get_template('grade/grade_list.html')
    return HttpResponse(template.render(data, request))


@my_custom_decorator
def duty_list(request):
    template = loader.get_template('duty/duty_list.html')
    return HttpResponse(template.render({'item_list': [1, 2, 3, 4, 5]}, request))


def duty_create_api(request):
    date = request.POST.get('date')
    # 查询所有的学生，将学生的姓名统一放在一个列表
    info = Student.objects.values('user_name')
    student_list = []
    for i in info:
        student_list.append(i['user_name'])
    # 应用random模块进行随机选择
    print(student_list)

    # 查询log中的人，生成列表，可以用集合，集合差集合
    log = DutyLog.objects.values('user_name')
    log_list = []
    for i in log:
        log_list.append(i['user_name'])

    set1 = set(student_list)
    set2 = set(log_list)
    difference_set = set1 - set2

    duty = random.choice(list(difference_set))
    print(duty)
    # 可以写一个值日生的log，把每次记录生成的人
    DutyLog.objects.create(user_name=duty, date_time=date)
    info = {
        "code": 0,
        "msg": '生成成功',
        "data": duty
    }
    return JsonResponse(info)


